<?php
namespace app\common\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
/**
 * Created by qihaoyingdi
 * Class CrawlRepo
 * Description:仓库爬取，每天凌晨执行一次
 * @package app\common\command
 * Author:sunnier
 * Email:xiaoyao_xiao@126.com
 * 2020-11-02 10:50
 */
class CrawlRepo  extends Command
{
	private $crawlRepoService;
	public function __construct($name = null)
	{
		parent::__construct($name);
		try {
			$this->crawlRepoService = app('app\common\service\CrawlRepoService');
		} catch (\Exception $e) {
			echo '--异常---'.$e->getMessage();
		}
	}

	protected function configure()
	{
		$this->setName('crawl_repo')
			->addArgument('date',Argument::OPTIONAL,'日期')
            ->addArgument('lang',Argument::OPTIONAL,'语言')
			->setDescription('爬取github的仓库排行');
	}

	/**
	 * @param Input $input
	 * @param Output $output
	 * @return int|void|null
	 */
	protected function execute(Input $input, Output $output)
	{
		$lang =$input->getArgument('lang');
		if(empty($lang)){
		    $langArr=config('language.data');
        }else{
		    if($lang!='all') {
                $langArr = [
                    [
                    'url_param' => strtolower($lang),
                    'name' => $lang
                    ]
                ];
            }else{
                $langArr = [
                        [
                        'url_param' =>'all',
                        'name' => $lang
                    ]
                ];
            }
        }
		//daily,weekly,monthly
        $date =$input->getArgument('date');
		try {
            foreach ($langArr as $lang) {
                $result = $this->crawlRepoService->crawler($lang['url_param'], $date);
                if ($result['status'] != 1) {
                    $output->writeln(date('Y-m-d H:i:s') . '处理数据出错：' . $result['msg']);
                    exit();
                }
                sleep(10);
            }
            $output->writeln(date('Y-m-d H:i:s') . '处理数据完成!'.$result['msg']);
            exit();
        }catch (\Exception $e){
            $output->writeln(date('Y-m-d H:i:s') . '处理数据出错：' . $e->getMessage());
            exit();
        }
	}
}